/*
* @Author: z.p
* @Project: Zdotp
* @Date: 2025年01月15日
* @Description: 对象池对象文件
*/

namespace Zdotp.ObjectPool;

public class PObject<T> : IObject where T : ObjectBase, new()
{
    private readonly T _data;
    private Action<T>? _init;
    private Action<T>? _callback;
    public bool IsUsing { get; private set; }
    public PObject(T data)
    {
        _data = data;
    }

    public T? GetObj(Action<T>? init = null, Action<T>? callback = null)
    {
        if (IsUsing) return null;
        IsUsing = true;
        
        _init = init;
        _callback = callback;
        
        _data.OnGet();
        _init?.Invoke(_data);
        return _data;
    }
    public bool ReleaseObj(T data)
    {
        if (data.ObjId != _data.ObjId) return false;
        if (!IsUsing) return false;
        IsUsing = false;
        
        data.OnRelease();
        _callback?.Invoke(_data);
        
        _init = null;
        _callback = null;
        
        return true;
    }

}

public interface IObject
{
    protected bool IsUsing { get; }
}

public abstract class ObjectBase
{
    public uint ObjId;
    public abstract void OnGet();
    public abstract void OnRelease();
}